<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/userStore';

const userStore = useUserStore();
const router = useRouter();
const activeIndex = ref("1");

// 导航方法
const goToLogin = () => router.push('/login');
const goToRegister = () => router.push('/register');
const goToProfile = () => router.push('/user'); // 跳转到用户信息页

// 退出登录方法
const handleLogout = () => {
  userStore.logout(); // 调用 store 的 logout 方法
  router.push('/'); // 退出后跳转到首页
};
</script>

<template>
  <el-container>
    <el-header>
      <el-row>
        <!-- Logo区域 -->
        <el-col :span="4" style="display: flex; align-items: center">
          <img src="/images/logo.png" style="height: 60px" />
          <h2 style="padding-left: 8px">技术社区</h2>
        </el-col>
        
        <!-- 导航菜单 -->
        <el-col :span="8" :xs="12">
          <el-menu
            :default-active="activeIndex"
            mode="horizontal"
            style="border-bottom: none !important"
            :ellipsis="false"
          >
            <el-menu-item index="1"><router-link to="/">首页</router-link></el-menu-item>
            <el-menu-item index="2">文章</el-menu-item>
            <el-menu-item index="3">课程</el-menu-item>
            <el-menu-item index="4"><router-link to="/mall">商城</router-link></el-menu-item>
          </el-menu>
        </el-col>
        
        <!-- 搜索框 -->
        <el-col :span="8" class="hidden-xs-only">
          <el-input placeholder="搜索..." />
        </el-col>
        
        <!-- 用户操作区 -->
        <el-col :span="4" class="hidden-xs-only">
          <div v-if="userStore.isLoggedIn">
            <!-- 修改点：使用 handleLogout 方法处理退出 -->
            <el-link type="primary" @click="handleLogout">退出</el-link>
            <!-- 修改点：添加点击事件跳转到用户信息页 -->
            <el-link type="primary" style="padding: 8px" @click="goToProfile">
              {{ userStore.user?.username || '用户' }}
            </el-link>
          </div>
          <div v-else>
            <el-link type="primary" @click="goToLogin">登录</el-link>
            <el-link type="primary" @click="goToRegister">注册</el-link>
          </div>
        </el-col>
      </el-row>
    </el-header>
  </el-container>
</template>